<?php

class Skjb_Controller_Plugin_Gzip extends Zend_Controller_Plugin_Abstract
{
    private $_compression = 1;
    
    /**
     * @param int $compression [optional] The gzip compression level to use when compressing the output
     */
    public function __construct($compression = 1)
    {
        $this->_compression = $compression;
    }
    
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
            return;
        } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) {
            $this->_response->setHeader('Content-Encoding', 'x-gzip', true);
        } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
            $this->_response->setHeader('Content-Encoding', 'gzip', true);
        } else {
            return;
        }
        $contents = $this->_response->getBody();
        $size = strlen($contents);
        $contents = gzcompress($contents, $this->_compression);
        $this->_response->setBody("\x1f\x8b\x08\x00\x00\x00\x00\x00" . $contents);
    }
}